package org.nobody.mallb2c.mallauth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.nobody.common.utils.HttpUtils;
import org.nobody.common.utils.R;
import org.nobody.mallb2c.mallauth.feign.MemberFeignService;
import org.nobody.common.vo.MemberRespVo;
import org.nobody.mallb2c.mallauth.vo.SocialUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 3489309323@qq.com
 * @create 2020-09-18-12:40
 */
@Slf4j
@Controller
public class OAuth2Controller {
  @Autowired
  MemberFeignService memberFeignService;

  @GetMapping("/oauth2.0/weibo/success")
  public String weibo(@RequestParam("code") String code, HttpSession httpSession) throws Exception {
    //第二步 根据code换取access_token
    Map<String, String> map = new HashMap<>();
    map.put("client_id", "1274611304");
    map.put("client_secret", "ae89978253abc5f905efebd6b6c33ae1");
    map.put("grant_type", "authorization_code");
    map.put("redirect_uri", "http://auth.mall.com/oauth2.0/weibo/success");
    map.put("code", code);
    HttpResponse response = HttpUtils.doPost("https://api.weibo.com", "/oauth2/access_token", "post", new HashMap<>(),new HashMap<>(), map);
    //第三步 根据access_token获取用户授权信息
    if (response.getStatusLine().getStatusCode() == 200) {
      String json = EntityUtils.toString(response.getEntity());
      SocialUser socialUser = JSON.parseObject(json, SocialUser.class);

      //知道当前是哪个社交用户
      //当前用户如果是第一次进网站,自动注册进来(为当前社交用户生成一个会员信息账号,以后这个社交账号就对应指定的会员)
      R r = memberFeignService.oauthLogin(socialUser);
      if (r.getCode() == 0) {
        MemberRespVo data = r.getData("data", new TypeReference<MemberRespVo>() {});

        log.info("登录成功,用户信息为: {}", data.toString());
        httpSession.setAttribute("loginUser", data);

        //登录成功就调回首页
        return "redirect:http://mall.com";
      }else{
        return "redirect:http://auth.mall.com/login.html";
      }

    //获取用户授权信息失败
    }else{
      return "redirect:http://auth.mall.com/login.html";
    }
  }
}
